package com.petShop.controllers;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.petShop.dao.GoodDao;
import com.petShop.models.Good;
import com.petShop.util.MyTool;


@Controller
@Transactional
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	GoodDao goodDao;

	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView get(){
		ModelAndView mav = new ModelAndView("/admin/index");
		return mav;
	}
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView post(@RequestParam String username,@RequestParam String password,HttpSession session){
		ModelAndView mav = new ModelAndView();
		if(username.equals("admin")&&password.equals("admin")){
			session.setAttribute("aUsername", username);
			String AdminReturnUrl = (String) session.getAttribute("AdminReturnUrl");
			//System.out.println("ADMIN "+returnUrl);
			if(AdminReturnUrl==null){
				mav.setViewName("redirect:/admin/addpets");
			}else{
				mav.setViewName("redirect:"+AdminReturnUrl);
			}
		}else{
			mav.addObject("error","用户名或密码错误");
			mav.setViewName("/admin/index");
		}
		return mav;
	}
	//宠物狗
	@RequestMapping(value="/addpets",method=RequestMethod.GET)
	public ModelAndView addpets(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/admin/addPets");
		return mav;
	}
	@RequestMapping(value="/addpets",method=RequestMethod.POST)
	public ModelAndView addpet(@RequestParam String name,@RequestParam String sex,
			@RequestParam String age,@RequestParam String color,@RequestParam String stock,
			@RequestParam String price,@RequestParam String kinds,@RequestParam String blood,
			@RequestParam MultipartFile img,HttpServletRequest request,HttpSession session) throws IllegalStateException, IOException{
		ModelAndView mav = new ModelAndView();
	
		mav.addObject("petMsg",setPet("insertPet",0,name,sex,age,color,stock,price,kinds,blood,img,request));
		mav.setViewName("/admin/addPets");
		
		return mav;
	}
	
	@RequestMapping(value="/petDetails",method=RequestMethod.GET)
	public ModelAndView petDetails(){
		ModelAndView mav = new ModelAndView();
		List<Good> pets = goodDao.selectPets();
		mav.addObject("pets", pets);
		mav.setViewName("/admin/petDetails");
		return mav;
	}
	
	@RequestMapping(value="/petDetails/{goodId}",method=RequestMethod.GET)
	public ModelAndView petModify(@PathVariable int goodId){
		ModelAndView mav = new ModelAndView();

		Good pet = goodDao.selectGood(goodId);
		mav.addObject("pet",pet);
	
		mav.setViewName("/admin/petModify");
		return mav;
	}
	
	@RequestMapping(value="/petDetails/{goodId}",method=RequestMethod.POST)
	public ModelAndView petModify(@PathVariable int goodId,@RequestParam String name,@RequestParam String sex,
			@RequestParam String age,@RequestParam String color,@RequestParam String stock,
			@RequestParam String price,@RequestParam String kinds,@RequestParam String blood,
			@RequestParam MultipartFile img,HttpServletRequest request) 
					throws IllegalStateException, IOException{
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("petMsg",setPet("updatePet",goodId,name,sex,age,color,stock,price,kinds,blood,img,request));
		
		Good pet = goodDao.selectGood(goodId);
		mav.addObject("pet",pet);
		mav.setViewName("/admin/petModify");
		return mav;
	}
	
	@RequestMapping(value="/deletepet",method=RequestMethod.GET)
	public ModelAndView petDelete(@RequestParam String goodId,HttpServletRequest request){
		ModelAndView mav = new ModelAndView();	
		
		if(goodId!=null){
			int id = Integer.parseInt(goodId);
			//删除goodImg
			Good g = goodDao.selectGood(id);
			String[] goodImgs = g.getGoodImg().split("/");
			String realPath=request.getSession().getServletContext().getRealPath("/");
			String path=realPath+"resources\\images\\"+goodImgs[0]+"\\"+goodImgs[1]+"\\"+goodImgs[2];	
			MyTool.deleteFile(path);
			
			goodDao.deleteGood(id);
		}

		mav.setViewName("redirect:/admin/petDetails");
		return mav;
	}
	//周边商品
	@RequestMapping(value="/addpetGoods",method=RequestMethod.GET)
	public ModelAndView addpetGoods(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/admin/addPetGoods");
		return mav;
	}
	
	@RequestMapping(value="/addpetGoods",method=RequestMethod.POST)
	public ModelAndView addpetGood(@RequestParam String name,@RequestParam String stock,
			@RequestParam MultipartFile img,@RequestParam String kinds,@RequestParam String price,
			@RequestParam String goodMsg,HttpServletRequest request) 
					throws IllegalStateException, IOException{
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("petGoodMsg",setPetGood("insertPetGood",0,name,stock,price,kinds,goodMsg,img,request));
		mav.setViewName("/admin/addPetGoods");
		return mav;
	}
	@RequestMapping(value="/petGoodDetails",method=RequestMethod.GET)
	public ModelAndView petGoodDetails(){
		ModelAndView mav = new ModelAndView();
		List<Good> petGoods = goodDao.selectPetGoods();
		mav.addObject("petGoods", petGoods);
		mav.setViewName("/admin/petGoodDetails");
		return mav;
	}
	
	@RequestMapping(value="/petGoodDetails/{goodId}",method=RequestMethod.GET)
	public ModelAndView petGoodModify(@PathVariable int goodId){
		ModelAndView mav = new ModelAndView();

		Good petGood = goodDao.selectGood(goodId);
		mav.addObject("petGood",petGood);
	
		mav.setViewName("/admin/petGoodModify");
		return mav;
	}
	
	@RequestMapping(value="/petGoodDetails/{goodId}",method=RequestMethod.POST)
	public ModelAndView petGoodModify(@PathVariable int goodId,@RequestParam String name,
			@RequestParam String stock,@RequestParam MultipartFile img,
			@RequestParam String price,@RequestParam String kinds,@RequestParam String goodMsg,
			HttpServletRequest request) 
					throws IllegalStateException, IOException{
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("petGoodMsg",setPetGood("updatePetGood",goodId,name,stock,price,kinds,goodMsg,img,request));
		
		Good petGood = goodDao.selectGood(goodId);
		mav.addObject("petGood",petGood);
		mav.setViewName("/admin/petGoodModify");
		return mav;
	}
	
	@RequestMapping(value="/deletepetGood",method=RequestMethod.GET)
	public ModelAndView petGoodDelete(@RequestParam String goodId,HttpServletRequest request){
		ModelAndView mav = new ModelAndView();	
		
		if(goodId!=null){
			int id = Integer.parseInt(goodId);
			//删除goodImg
			Good g = goodDao.selectGood(id);
			String[] goodImgs = g.getGoodImg().split("/");
			String realPath=request.getSession().getServletContext().getRealPath("/");
			String path=realPath+"resources\\images\\"+goodImgs[0]+"\\"+goodImgs[1]+"\\"+goodImgs[2];	
			MyTool.deleteFile(path);
			
			goodDao.deleteGood(id);
		}

		mav.setViewName("redirect:/admin/petGoodDetails");
		return mav;
	}
	
	public String setPet(String action,int id,String name,String sex,String age, String color, String stock,
			 String price, String kinds, String blood,MultipartFile img,HttpServletRequest request) 
					 throws IllegalStateException, IOException{
		int petAge = 0;
		int petStock = 0;
		float petPrice = 0;
		int kindsId = 0;
		if((action.equals("updatePet")||action.equals("insertPet"))&&!name.equals("")&&sex!=null&&!age.equals("")&&!color.equals("")&&!stock.equals("")&&!price.equals("")
				&&!kinds.equals("0")&&!blood.equals("")&&!img.isEmpty()){
			petAge = Integer.parseInt(age);
			petStock =  Integer.parseInt(stock);
			petPrice = Float.parseFloat(price);
			kindsId = Integer.parseInt(kinds);
			
			Good pet = new Good();
			pet.setGoodId(id);
			pet.setGoodName(name);
			pet.setSex(sex);
			pet.setAge(petAge); 
			pet.setColor(color);
			pet.setStock(petStock);
			pet.setKindsId(kindsId);
			pet.setPrice(petPrice);
			pet.setBlood(blood);
			
			return upload(action,pet,img,request);		
		}else if(action.equals("updatePet")&&!name.equals("")&&sex!=null&&!age.equals("")&&!color.equals("")&&!stock.equals("")&&!price.equals("")
				&&!kinds.equals("0")&&!blood.equals("")&&img.isEmpty()){
			petAge = Integer.parseInt(age);
			petStock =  Integer.parseInt(stock);
			petPrice = Float.parseFloat(price);
			kindsId = Integer.parseInt(kinds);
			
			Good pet = new Good();
			pet.setGoodId(id);
			pet.setGoodName(name);
			pet.setSex(sex);
			pet.setAge(petAge); 
			pet.setColor(color);
			pet.setStock(petStock);
			pet.setKindsId(kindsId);
			pet.setPrice(petPrice);
			pet.setBlood(blood);
			
			Good g = goodDao.selectGood(id);
			if(g.getKindsId()!=kindsId){
				String goodImg = g.getGoodImg();
				String[] goodImgs = goodImg.split("/");
				String newfileName = MyTool.setFilename(kinds);
				String realPath=request.getSession().getServletContext().getRealPath("/");
				MyTool.moveFile(realPath,goodImgs,newfileName);
				
				pet.setGoodImg(goodImgs[0]+"/"+newfileName+"/"+goodImgs[2]);
				goodDao.updatePet(pet);
				
			}
			goodDao.updatePet2(pet);
			return "更新成功";
		}else{
			return "请输入完整信息";
		}		
	}
	public String setPetGood(String action,int id,String name,String stock,String price,String kinds,String goodMsg,
			MultipartFile img,HttpServletRequest request) throws IllegalStateException, IOException{
		int petGoodStock = 0;
		float petGoodPrice = 0;
		int kindsId = 0;
		
		if((action.equals("updatePetGood")||action.equals("insertPetGood"))&&!name.equals("")&&!stock.equals("")&&!price.equals("")
				&&!kinds.equals("0")&&!goodMsg.equals("")&&!img.isEmpty()){
			
			petGoodStock =  Integer.parseInt(stock);
			petGoodPrice = Float.parseFloat(price);
			kindsId = Integer.parseInt(kinds);
			
			Good petGood = new Good();
			petGood.setGoodId(id);
		    petGood.setGoodName(name);
		   
		    petGood.setStock(petGoodStock);
		    petGood.setKindsId(kindsId);
		    petGood.setPrice(petGoodPrice);
		    petGood.setGoodMsg(goodMsg);
			return upload(action,petGood,img,request);		
		}else if(action.equals("updatePetGood")&&!name.equals("")&&!stock.equals("")&&!price.equals("")
				&&!kinds.equals("0")&&!goodMsg.equals("")&&img.isEmpty()){
			petGoodStock =  Integer.parseInt(stock);
			petGoodPrice = Float.parseFloat(price);
			kindsId = Integer.parseInt(kinds);
			
			Good petGood = new Good();
			petGood.setGoodId(id);
			petGood.setGoodName(name);
			petGood.setStock(petGoodStock);
		    petGood.setKindsId(kindsId);
		    petGood.setPrice(petGoodPrice);
		    petGood.setGoodMsg(goodMsg);
		    
			Good g = goodDao.selectGood(id);
			if(g.getKindsId()!=kindsId){
				String goodImg = g.getGoodImg();
				String[] goodImgs = goodImg.split("/");
				String newfileName = MyTool.setFilename(kinds);
				String realPath=request.getSession().getServletContext().getRealPath("/");
				MyTool.moveFile(realPath,goodImgs,newfileName);
				
				petGood.setGoodImg(goodImgs[0]+"/"+newfileName+"/"+goodImgs[2]);
				goodDao.updatePetGoods(petGood);
			}else{
				goodDao.updatePetGoods2(petGood);
			}			
			return "更新成功";
		}
		else{
			return "请输入完整信息";			
		}		
	}
	
	public String upload(String action,Good good,MultipartFile img,
			HttpServletRequest request) throws IllegalStateException, IOException{
		if(!img.isEmpty()){
		    String path=null;// 文件路径
		    String type=null;// 文件类型
		    String fileName=img.getOriginalFilename();// 文件原名称
		    //System.out.println("上传的文件原名称:"+fileName);
		    // 判断文件类型
		    type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
		    				    
		    if (type!=null) {// 判断文件类型是否为空
			    if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
				    // 项目在容器中实际发布运行的根路径
				    String realPath=request.getSession().getServletContext().getRealPath("/");
				    // 自定义的文件名称
				    String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
				    String filename = MyTool.setFilename(good.getKindsId()+"");//判断种类设置文件名
				    String str = "";
				    if(action.equals("insertPet")){					    
					    // 设置存放图片文件的路径
					    path=realPath+"resources\\images\\pets\\"+filename+"\\"+trueFileName;				    
					    // 转存文件到指定的路径
					    img.transferTo(new File(path));
					    
					    good.setGoodImg("pets/"+filename+"/"+trueFileName);
					    goodDao.insertPet(good);
					    
					    str="添加";
				    }else if(action.equals("insertPetGood")){
				    	path=realPath+"resources\\images\\petGoods\\"+filename+"\\"+trueFileName;
					    img.transferTo(new File(path));
					    
					    good.setGoodImg("petGoods/"+filename+"/"+trueFileName);
					    goodDao.insertPetGood(good);
					    str="添加";
				    }else if(action.equals("updatePet")){
					    path=realPath+"resources\\images\\pets\\"+filename+"\\"+trueFileName;				    
					    img.transferTo(new File(path));
					    
					    //删除goodImg
						Good g = goodDao.selectGood(good.getGoodId());
						String[] goodImgs = g.getGoodImg().split("/");
						path=realPath+"resources\\images\\"+goodImgs[0]+"\\"+goodImgs[1]+"\\"+goodImgs[2];	
						MyTool.deleteFile(path);
					    
					    good.setGoodImg("pets/"+filename+"/"+trueFileName);
					    goodDao.updatePet(good);
					    
					    str="更新";
				    }else if(action.equals("updatePetGood")){
					    path=realPath+"resources\\images\\petGoods\\"+filename+"\\"+trueFileName;			    
					    img.transferTo(new File(path));
					    
					    //删除goodImg
						Good g = goodDao.selectGood(good.getGoodId());
						String[] goodImgs = g.getGoodImg().split("/");
						path=realPath+"resources\\images\\"+goodImgs[0]+"\\"+goodImgs[1]+"\\"+goodImgs[2];	
						MyTool.deleteFile(path);
						
				    	good.setGoodImg("petGoods/"+filename+"/"+trueFileName);
					    goodDao.updatePetGoods(good);
					    
					    str="更新";
				    }
				    return str+"成功";				  
			    }else {
				    return "文件类型错误,请按要求重新上传";					
			    }
		    }else {
		    	return "文件类型为空";  
		    }		    
		}else {
			return "没有找到相对应的文件";				
		}	
	}
	
	
}
